import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/Invitebox/Invite_box_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/main.dart';
import 'package:nft_shop/my/page/invite/my_invite_page.dart';
import 'package:nft_shop/my/page/my_list_page.dart';
import 'package:nft_shop/my/page/my_list_type_page.dart';
import 'package:nft_shop/my/page/notice/my_message_page.dart';
import 'package:nft_shop/my/page/order/my_order_page.dart';
import 'package:nft_shop/my/page/set/my_authentication_page.dart';
import 'package:nft_shop/my/page/set/my_infodata_page.dart';
import 'package:nft_shop/my/page/set/my_set_page.dart';
import 'package:nft_shop/my/page/wallet/my_wallet_page.dart';
import 'package:nft_shop/my/page/write/my_write_page.dart';
import 'package:nft_shop/my/view/album_hint.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/sift/page/sift_page.dart';
import 'package:nft_shop/util/log_utils.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/custom_underline_tabIndicator.dart';
import 'package:nft_shop/widgets/load_image.dart';

import '../conteroller/my_conteroller.dart';

class MyPage extends StatefulWidget {
  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage>
    with SingleTickerProviderStateMixin, RouteAware {
  TabController? _tabController;
  final PageController _pageController = PageController(initialPage: 0);

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventBus.on<String>().listen((it) {
      if (it == "logout") {
        _jumpToPage(0);
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print("我的刷新-1");
    if (_tabController == null) {
      _tabController = TabController(vsync: this, length: 3);
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "我的",
          style: TextStyle(
              fontSize: 16,
              color: Global.kTheme.colorBackground1,
              fontFamily: Global.mySemiboldFont),
        ),
        centerTitle: true,
        actions: [
          IconButton(
              icon: LoadAssetImage(
                "my_message",
                width: 20,
                height: 20,
              ),
              onPressed: () {
                Get.to(() => HomeMessagePage());
              }),
          IconButton(
              icon: LoadAssetImage(
                "my_set",
                width: 20,
                height: 20,
              ),
              onPressed: () {
                Get.to(() => MySetPage());
              }),
        ],
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [
              Color(0xFF363636),
              Color(0xFF2A2A2A),
            ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
          ),
        ),
      ),
      body: NestedScrollView(
        physics: const ClampingScrollPhysics(),
        headerSliverBuilder: (context, innerBoxIsScrolled) =>
            _sliverBuilder(context),
        body: PageView.builder(
          key: const Key('pageView'),
          itemCount: 4,
          onPageChanged: _onPageChange,
          controller: _pageController,
          itemBuilder: (_, index) => MyListPage(index: index + 1),
        ),
      ),
    );
  }

  //置顶
  List<Widget> _sliverBuilder(BuildContext context) {
    return <Widget>[
      //头部
      SliverToBoxAdapter(
        child: Container(
          height: 170 + 35,
          color: Colors.white,
          child: GetBuilder<UserController>(
              id: UserController.UserInfo,
              builder: (logic) {
                return Stack(
                  children: [
                    Container(
                      height: 170,
                      padding: EdgeInsets.only(left: 20, right: 18, top: 16),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [
                              Color(0xFF2A2A2A),
                              Color(0xFF222222),
                            ],
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter),
                      ),
                      child: Column(
                        children: [
                          InkWell(
                            onTap: () => Get.to(() => MyInfoDataPage()),
                            child: Row(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(21),
                                  child: LoadImage(
                                    logic.isLogin
                                        ? logic.member.portrait ?? ""
                                        : "",
                                    holderImg: "header_img",
                                    width: 42,
                                    height: 42,
                                  ),
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text.rich(TextSpan(children: [
                                        TextSpan(
                                          text: logic.isLogin
                                              ? logic.loginuser!.member!
                                                      .nickname ??
                                                  ""
                                              : "登录/注册",
                                          style: TextStyle(
                                              fontSize: 20,
                                              color: Global.kTheme.textPrimary5,
                                              fontFamily:
                                                  Global.mySemiboldFont),
                                        ),
                                        WidgetSpan(
                                          child: SizedBox(
                                            width: 4,
                                          ),
                                        ),
                                        WidgetSpan(
                                            child: Visibility(
                                          visible: logic.loginuser!.member!
                                                      .realNameStatus ==
                                                  "1"
                                              ? true
                                              : false,
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 4, vertical: 2),
                                            decoration: BoxDecoration(
                                              color: Color(0xFF50E3C2),
                                              borderRadius:
                                                  BorderRadius.circular(2),
                                            ),
                                            child: Text(
                                              getUserState(logic.loginuser
                                                  ?.member?.realNameStatus),
                                              style: TextStyle(
                                                  fontSize: 8,
                                                  color: Global
                                                      .kTheme.textPrimary5),
                                            ),
                                          ),
                                        )),
                                      ])),

                                      // Row(
                                      //   children: [
                                      //     Text(
                                      //       logic.isLogin?logic.loginuser!.member!.nickname??"":"登录/注册",
                                      //       maxLines:1,
                                      //       overflow:TextOverflow.ellipsis,
                                      //       style: TextStyle(
                                      //           fontSize: 20,
                                      //           color: Global.kTheme.textPrimary5,
                                      //           fontFamily: Global.mySemiboldFont),
                                      //     ),
                                      //     SizedBox(
                                      //       width: 4,
                                      //     ),
                                      //     Visibility(
                                      //       visible: true,
                                      //       child: Container(
                                      //         padding: EdgeInsets.symmetric(
                                      //             horizontal: 4, vertical: 2),
                                      //         decoration: BoxDecoration(
                                      //           color: Color(0xFF50E3C2),
                                      //           borderRadius: BorderRadius.circular(2),
                                      //         ),
                                      //         child: Text(
                                      //           "已实名",
                                      //           style: TextStyle(
                                      //               fontSize: 8,
                                      //               color: Global.kTheme.textPrimary5),
                                      //         ),
                                      //       ),
                                      //     ),
                                      //   ],
                                      // ),
                                      SizedBox(
                                        height: 1,
                                      ),
                                      InkWell(
                                        onTap: () {
                                          ClipboardData data =
                                              new ClipboardData(
                                                  text: UserController.to.member
                                                          .accountAddress ??
                                                      "");
                                          Clipboard.setData(data);
                                          EasyLoading.showToast("复制成功");
                                        },
                                        child: Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Text(
                                              logic.isLogin
                                                  ? omitAddress(logic
                                                          .loginuser!
                                                          .member!
                                                          .accountAddress ??
                                                      "")
                                                  : "",
                                              style: TextStyle(
                                                  fontSize: 12,
                                                  color: Global
                                                      .kTheme.textPrimary5,
                                                  fontFamily: Global.myDINFont),
                                            ),
                                            SizedBox(
                                              width: 7,
                                            ),
                                            logic.isLogin
                                                ? LoadAssetImage(
                                                    "my_copy",
                                                    width: 16,
                                                    height: 16,
                                                  )
                                                : Container(),
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                LoadAssetImage(
                                  "my_edit",
                                  width: 16,
                                  height: 17,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Positioned(
                      bottom: 10,
                      left: 15,
                      right: 15,
                      child: Container(
                        height: 95,
                        padding: const EdgeInsets.only(left: 10, right: 10),
                        decoration: BoxDecoration(
                          color: Global.kTheme.colorBackground1,
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                                offset: Offset(0.0, 2.0), //x,y轴
                                color: Color(0x80CCCCCC), //投影颜色
                                blurRadius: 8 //投影距离
                                )
                          ],
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            _buildItem(
                              "icon_qianbao",
                              "我的钱包",
                              () => Get.to(() => MyWalletPage()),
                            ),
                            _buildItem(
                              "icon_order",
                              "我的订单",
                              () => Get.to(() => MyOrderPage()),
                            ),
                            _buildItem("icon_chuangzuo", "实名认证", () {
                              // String realNameStatus = getUserState(
                              //     logic.loginuser?.member?.realNameStatus);
                              // if (realNameStatus == "已实名") {
                              //   return;
                              // }
                              // if (realNameStatus == "审核中") {
                              //   EasyLoading.showToast("存在待审核申请,请等待审核结果");
                              //   return;
                              // }
                              // Get.to(MyAuthenticationPage());
                              Get.to(MyInfoDataPage());
                            }),
                            // _buildItem("icon_chuangzuo", "创作服务", () {
                            //   if (logic.member.castRole == "0") {
                            //     EasyLoading.showToast("请联系客服开通创作者服务权限");
                            //     return;
                            //   } else if (UserController
                            //           .to.member.realNameStatus !=
                            //       "2") {
                            //     if (UserController.to.member.realNameStatus ==
                            //         "1") {
                            //       EasyLoading.showToast("存在待审核申请,请等待审核结果");
                            //       return;
                            //     }
                            //
                            //     Utils.showElasticDialog<void>(
                            //       context: context,
                            //       barrierDismissible: false,
                            //       builder: (BuildContext context) {
                            //         return AuthenticationDialog();
                            //       },
                            //     );
                            //     return;
                            //   }
                            //   Get.to(() => MyWritePage());
                            // }),
                            _buildItem("invite_friends", "邀请好友", () {
                              Get.to(() => MyInvitePage());
                            }),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              }),
        ),
      ),
      SliverToBoxAdapter(
        child: Container(
          height: 45,
          margin: EdgeInsets.symmetric(horizontal: 14, vertical: 5),
          padding: EdgeInsets.only(left: 20, right: 13),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            gradient: LinearGradient(colors: [
              Color(0xFF474747),
              Color(0xFF222222),
            ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
          ),
          child: Row(
            children: [
              LoadAssetImage(
                "my_pavilion",
                width: 19,
                height: 19,
              ),
              SizedBox(
                width: 5,
              ),
              Text(
                "只属于我的藏品阁楼",
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary5,
                    fontWeight: FontWeight.w500),
              ),
              Spacer(),
              InkWell(
                onTap: () {
                  EasyLoading.showToast("敬请期待");
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    gradient: LinearGradient(colors: [
                      Color(0xFFE5AE58),
                      Color(0xFFFCD79E),
                    ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
                  ),
                  child: Text(
                    "开启展馆",
                    style: TextStyle(
                        fontSize: 12,
                        color: Color(0xFF212121),
                        fontFamily: Global.mySemiboldFont),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      //选项卡
      SliverPersistentHeader(
        pinned: true,
        delegate: SliverAppBarDelegate(
          DecoratedBox(
            decoration: BoxDecoration(color: Global.kTheme.colorBackground1),
            child: tabsWidget(),
          ),
          44.0,
        ),
      ),
    ];
  }

  Widget _buildItem(String icon, String title, VoidCallback onPressed) {
    return InkWell(
      onTap: onPressed,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          LoadAssetImage(
            icon,
            width: 28,
            height: 28,
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            title,
            style: TextStyle(
                fontSize: 12,
                color: Global.kTheme.inputHint1,
                fontFamily: Global.mySemiboldFont),
          )
        ],
      ),
    );
  }

  ///选项卡
  Widget tabsWidget() {
    return TabBar(
      isScrollable: true,
      controller: _tabController,
      labelStyle: TextStyle(
        fontSize: 15,
        fontFamily: Global.mySemiboldFont,
      ),
      unselectedLabelStyle: TextStyle(
        fontSize: 15,
        fontFamily: Global.mySemiboldFont,
      ),
      indicatorSize: TabBarIndicatorSize.label,
      unselectedLabelColor: Global.kTheme.textPrimary3,
      labelColor: Global.kTheme.textPrimary4,
      indicatorPadding: EdgeInsets.only(bottom: 2, left: 15, right: 15),
      indicator: CustomUnderlineTabIndicator(
          borderSide: BorderSide(
        color: Global.kTheme.textPrimary4,
        width: 3,
      )),
      tabs: const <Widget>[
        Tab(
          text: "我拥有的",
        ),
        Tab(
          text: "我卖出的",
        ),
        Tab(
          text: "售卖中",
        ),
      ],
      onTap: (index) {
        if (!mounted) {
          return;
        }
        _jumpToPage(index);
      },
    );
  }

  void _onPageChange(int index) {
    _tabController?.animateTo(index);
  }

  void _jumpToPage(int index) {
    _pageController.jumpToPage(index);
    MyConteroller.to.sectionIndex = index + 1;
    MyConteroller.to.refreshData();
  }

  String omitAddress(String address, {int len = 4}) {
    if (address == null || address.isEmpty) return "";
    if (address.length > (len * 2)) {
      return address.substring(0, len) +
          '...' +
          address.substring(address.length - len, address.length);
    }
    return address;
  }

  ///获取身份审核状态
  String getUserState(String? realNameStatus) {
    String status = "未实名";
    if (realNameStatus == null && realNameStatus == "") {
      status = "0";
    }
    //是否完成身份认证 0未提交 1待审核 2审核通过 3驳回
    if (realNameStatus == "0") {
      status = "未实名";
    } else if (realNameStatus == "1") {
      status = "审核中";
    } else if (realNameStatus == "2") {
      status = "已实名";
    } else if (realNameStatus == "3") {
      status = "驳回";
    }

    return status;
  }
}
